/*
 * @Author: C.
 * @Date: 2023-11-30 15:23:05
 */
import { computed, nextTick, ref, unref, watch } from 'vue'
import useMescroll from '@/uni_modules/uni-scroll/hooks/useMescroll.js'

export function useListScroll({ load, setSuccessCb, setErrorCb }) {
  const mescrollRef = ref<Recordable>({})
  const { mescrollInit, getMescroll } = useMescroll()
  const upOption = {
    noMoreSize: 3, //如果列表已无数据, 可设置列表的总数量要大于半页才显示无更多数据;避免列表数据过少(比如只有一条数据),显示无更多数据会不好看
    empty: {
      tip: '~ 搜索无结果 ~', // 提示
    },
    // auto: true
  }
  const downOption = {
    auto: false, //是否在初始化后,自动执行downCallback; 默认true
  }
  /*上拉加载的回调: 其中mescroll.num:当前页 从1开始, mescroll.size:每页数据条数,默认10  */
  const upCallback = (mescroll: any) => {
    mescrollRef.value = mescroll
    load({
      PageSize: mescroll.size,
      CurrentPage: mescroll.num,
    })
  }
  const downCallback = (mescroll: any) => {
    mescrollRef.value = mescroll
    getMescroll().resetUpScroll()
  }
  function endBySize(len: number, count: number) {
    mescrollRef.value.endBySize(len, count)
  }
  function endErr() {
    mescrollRef.value.endErr()
  }
  function resetUpScroll() {
    getMescroll().scrollTo(0, 100)
    nextTick(() => {
      getMescroll().resetUpScroll()
    })
  }
  setSuccessCb(endBySize)
  setErrorCb(endErr)
  const getScrollBind = computed(() => {
    return {
      upOption,
      downOption,
      onInit: mescrollInit,
      onDown: downCallback,
      onUp: upCallback,
    }
  })
  return {
    getScrollBind,
    resetUpScroll,
    getMescroll,
  }
}
